<?php

namespace app\common\model;

use think\Model;

class SearchCount extends Model
{
    // 表名
    protected $name = 'search_count';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    
    // 追加属性
    protected $append = [
        'create_time_text',
        'update_time_text'
    ];
    

    



    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['create_time'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getUpdateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['update_time'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setCreateTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setUpdateTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }
	
	
	/**
	 * 统计搜索数量
	 * @param $keyword 关键字
	 * @throws \think\Exception
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
    public function addRecord($keyword){
        $row = $this->where(['keyword' => $keyword])->find();
        if($row) {
        	$row->setInc('numbers');
        } else {
        	$this->isUpdate(false)->save([
        	    'keyword' => $keyword,
		        'numbers' => 1,
	        ]);
        }
    }
}
